package com.dyrj.ysk.controller;

import com.alibaba.fastjson.JSON;
import com.dyrj.ysk.configuration.SdkProperties;
import com.dyrj.ysk.constants.PayModeNo;
import com.dyrj.ysk.entity.JsapiPayResp;
import com.dyrj.ysk.util.FakeDataUtil;
import com.dyrj.ysk.util.HttpUtil;
import com.dyrj.ysk.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * 公众号支付
 * @author 吴侠志  2020/1/7
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/ysksdk")
public class JsapiPayController {
    @Autowired
    private SdkProperties sdkProperties;

    /**
     * 公众号支付
     * @return
     */
    @RequestMapping(value = "/jsapiPay",method = RequestMethod.GET)
    public String jsapiPay(HttpServletRequest request, Model model) throws Exception {
        Map<String,String> reqParam=new HashMap<>();
        //必填 商户编号
        reqParam.put("businessNo",sdkProperties.getBusinessId());
        //必填 商户订单号 商户系统生成的订单号，需要保证在商户系统唯一
        reqParam.put("outNo", FakeDataUtil.randomTraderOrderNo());
        //非必填 门店编号
        reqParam.put("StoreId",null);
        //必填 交易金额 单位：分
        reqParam.put("tradeAmount","1");
        //必填 订单发送时间 格式：yyyyMMddHHmmss
        reqParam.put("addTime",FakeDataUtil.orderSendTimeNow());
        //非必填 订单名称
        reqParam.put("name","一笔订单");
        //非必填 订单详情
        reqParam.put("body","这是一笔订单");
        //非必填 备注
        reqParam.put("remark","这是啥啊");
        //非必填 回调通知URL
        reqParam.put("notifyUrl",FakeDataUtil.callBackNoticeUrl());
        //非必填 前端跳转URL
        reqParam.put("jumpUrl",FakeDataUtil.frontSkipUrl());
        //必填 支付方式编号 只有WeixinJsapi和AlipayJsapi可选
        String userAgent = request.getHeader("user-agent");
        if (userAgent != null && userAgent.contains("AlipayClient")) {
            reqParam.put("payWayCode", PayModeNo.ALIPAY_JSAPI.getCode());
        }else if (userAgent != null && userAgent.contains("MicroMessenger")) {
            reqParam.put("payWayCode", PayModeNo.WEIXIN_JSAPI.getCode());
        }else{
            model.addAttribute("errorMessage","请使用支付宝或者微信进行访问");
            return "error";
        }
        String req=JSON.toJSONString(reqParam);
        log.info(req);
        String resp= HttpUtil.post(sdkProperties.getJsapiPayUrl(),req);
        log.info(resp);
        JsapiPayResp respObj= JsonUtil.jsonToPoJo(resp,JsapiPayResp.class);
        if(respObj.getSuccess() == null){
            model.addAttribute("errorMessage",respObj.getResultMessage());
            return "error";
        }
        return "redirect:"+sdkProperties.getJsapiPayFrontUrl()+"?token="+respObj.getData().getToken();
    }
}
